<template>
  <main-content
    title="员工管理"
    :back="true"
  >
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <!--          <el-form-item>-->
          <!--            <el-select-->
          <!--                v-model="params.insId"-->
          <!--                placeholder="请选择所属机构"-->
          <!--                clearable-->
          <!--            >-->
          <!--              <el-option-->
          <!--                  :label="item.name"-->
          <!--                  :value="item.id"-->
          <!--                  :key="item.id"-->
          <!--                  v-for="item in orgList"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-input
              v-model="params.name"
              placeholder="员工名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="params.status"
              placeholder="状态"
              clearable
            >
              <el-option
                label="启用"
                :value="1"
              />
              <el-option
                label="停用"
                :value="0"
              />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="getStaffPageList"
            >
              查询
            </el-button>

            <el-button
              v-has="['1015']"
              type="primary"
              icon="Plus"
              @click="addStaff"
            >
              新增
            </el-button>
            <!-- TODO 加权限 -->
            <el-button
              type="primary"
              @click="showExportData = true"
            >
              导出
            </el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <el-table
      v-loading="state.isLoading"
      :data="state.tableData"
      row-key="id"
      stripe
      default-expand-all
    >
      <el-table-column
        prop="realName"
        label="员工姓名"
        min-width="180"
      />
      <el-table-column
        prop="insName"
        label="所属机构"
        min-width="150"
      />
      <el-table-column
        prop="roleName"
        label="当前职务"
        width="150"
      />
      <el-table-column
        prop="empNo"
        label="员工号"
        width="120"
      />
      <el-table-column
        prop="username"
        label="登录账号"
        width="100"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="100"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            class="ml-2"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="bindWechat"
        label="是否绑定微信"
        width="180"
      >
        <template #default="scope">
          {{ scope.row.bindWechat ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="160"
      >
        <template #default="scope">
          {{ new Date(scope.row.updateTime).format("yyyy-MM-dd hh:mm") }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="230"
      >
        <template #default="scope">
          <el-button
            v-if="!scope.row.bindWechat"
            link
            type="primary"
            size="small"
            @click="showWechatBindDialog(scope.row)"
          >
            绑定微信
          </el-button>
          <el-button
            v-else
            link
            type="danger"
            size="small"
            @click="_unbindWechat(scope.row)"
          >
            解绑微信
          </el-button>
          <el-button
            v-has="['1016']"
            link
            type="primary"
            size="small"
            @click="editStaffForm(scope.row.id)"
          >
            编辑
          </el-button>
          <el-dropdown
            placement="top"
            @command="handleCommand($event, scope.row)"
          >
            <div style="margin-left: 10px; cursor: pointer">
              <el-button
                v-has="['1017', '1018']"
                type="primary"
                link
                size="small"
              >
                更多
              </el-button>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="scope.row.status"
                  v-has="['1017']"
                  command="updateStaffStatus"
                >
                  停用
                </el-dropdown-item>
                <el-dropdown-item
                  v-else
                  v-has="['1017']"
                  command="updateStaffStatus"
                >
                  启用
                </el-dropdown-item>
                <el-dropdown-item
                  v-has="['1018']"
                  command="delStaff"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        v-model:currentPage="params.current"
        v-model:page-size="params.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </main-content>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="50%"
    :before-close="resetForm"
    :close-on-click-modal="false"
  >
    <el-form
      ref="staffForm"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <ins-cascader-filter
        v-model:selected="editInsIdModel"
        :clearable="false"
        :cascader-props="{multiple: false}"
      />

      <el-form-item
        label="员工姓名"
        prop="realName"
      >
        <el-input
          v-model="form.realName"
          autocomplete="off"
          placeholder="员工姓名"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="员工号">
        <el-input
          v-model="form.empNo"
          autocomplete="off"
          placeholder="员工号"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="员工职务"
        prop="roleId"
      >
        <el-select
          v-model="form.roleId"
          placeholder="请选择职务"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="员工账号"
        prop="username"
      >
        <el-input
          v-model="form.username"
          autocomplete="off"
          placeholder="员工账号"
          maxlength="20"
          show-word-limit
          :disabled="edit"
        />
      </el-form-item>
      <el-form-item
        label="员工密码"
        prop="password"
      >
        <el-input
          v-model="form.password"
          autocomplete="off"
          placeholder="设置6至20位员工密码"
        />
      </el-form-item>
      <el-form-item label="数据权限">
        <el-radio-group v-model="form.dataAuth">
          <el-radio
            :label="0"
            name="type"
          >
            个人<span class="intro">只能操作自己的数据</span>
          </el-radio>
          <el-radio
            :label="1"
            name="type"
          >
            所属机构<span class="intro">能操作自己和自己所属机构的数据</span>
          </el-radio>
          <el-radio
            :label="2"
            name="type"
          >
            所属机构及下属机构
            <span class="intro">所属机构及下属机构能操作自己和自己所属机构及其子机构的数据</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm()">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm(staffForm, edit)"
        >保存</el-button>
      </span>
    </template>
  </el-dialog>

  <bind-wechat
    v-model:show="isShowBindWechat"
    :row-data="currentUserInfo"
    @bind-finished="handleBindWechatFinished"
  />
  <exportData
    v-model:show-dialog="showExportData"
    :search-data="{ userType: 'merchant', ...params }"
    title="员工管理"
    export-type="adminUserExport"
  />
</template>
<script lang="ts">
export default {
  name: 'StaffManagement'
}
</script>
<script lang="ts" setup>
import type { InternalRuleItem } from "async-validator"
import type { FormInstance } from "element-plus";
import { reactive, onMounted, Ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import exportData from "@/components/exportData/exportData.vue";
import {
  pageList,
  addNew,
  update,
  upStatus,
  detail,
  del,
} from "@/api/orgStaff";
import { allRole } from "@/api/orgPosition";
import { allOrg } from "@/api/orgManage";
import { staffReq } from "@/api/modules/orgStaff";
import { positionReq } from "@/api/modules/orgPosition";
import { filterTemplate } from "@/api/modules/orgManage";
import { debounceUtils } from "@/utils/index.js";
import { useBindWechat } from "@/views/organization/compositions/useBindWechat";
import BindWechat from "@/views/organization/components/staff/BindWechat.vue";

const route = useRoute();
const store = useStore()
const showExportData = ref(false)
const state = reactive({
  id: "",
  isLoading: false,
  total: 0,
  tableData: [] as Array<staffReq>,
});
const params = ref({
  insId: store.state.user.insId,
  name: "",
  status: "",
  size: 10,
  current: 1,
});
let roleList = ref([] as Array<positionReq>);
let orgList = ref([] as Array<filterTemplate>);
let form = ref({
  insId: 0,
  id: "",
  realName: "",
  empNo: "",
  roleId: "",
  username: "",
  password: "",
  dataAuth: 0,
});

const editInsIdModel: Ref<number[] | number> = ref(0);
watch(editInsIdModel, (newValue) => {
  if (typeof newValue === 'number') {
    form.value.insId = newValue
  } else if (newValue instanceof Array) {
    form.value.insId = newValue[newValue.length - 1]
  }
})

const validatePass = (rule: InternalRuleItem, value: string, callback: (e?: string | Error) => void) => { 
  // 新增时需输入员工密码
  if (!value && !edit.value) {
    callback("新增时请输入员工密码")
    return
  }
  // 编辑时可为空
  if (!value && edit.value) {
    callback()
    return
  }

  if (!/^[a-zA-Z0-9]{6,20}$/.test(value)) {
    callback("密码为6至20位字母或数字")
    return
  }
  
  callback();
};
const handleSizeChange = (val: number) => {
  params.value.size = val;
};
const handleCurrentChange = (val: number) => {
  params.value.current = val;
};
const staffForm = ref<FormInstance>();
let edit = ref(false);
const rules = computed(() => ({
  realName: [
    {
      required: true,
      message: "请输入员工名称",
      trigger: "blur",
    },
  ],
  roleId: [
    {
      required: true,
      message: "请选择职务",
      trigger: "change",
    },
  ],
  username: [
    {
      required: true,
      message: "请输入员工账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      validator: validatePass,
      required: !edit.value, // 新增员工时必填
      trigger: "blur",
    },
  ],
}));
const dialogFormVisible = ref(false);

let title = ref("新增员工");

const addStaff = () => {
  editInsIdModel.value = insId.value
  title.value = "新建员工";
  edit.value = false;
  dialogFormVisible.value = true;
};
const delStaff = (id: string | number) => {
  ElMessageBox.confirm("是否确定删除员工", "确认提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await del({
        id: id,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getStaffPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getStaffPageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await pageList(params.value);
  if (rs.code == 200) {
    state.tableData = rs.payload;
    state.total = rs.page.totalResult;
  }
  state.isLoading = false;
}, 500);
const editStaffForm = async (id: string | number): Promise<void> => {
  const rs = await detail({ id: id });
  if (rs.code == 200) {
    Object.assign(form.value, {
      ...rs.payload,
    });

    editInsIdModel.value = rs.payload.insId
    title.value = "编辑员工";
    edit.value = true;
    dialogFormVisible.value = true;
  }
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let rs;
      // form.value.insId = params.value.insId;
      if (edit) {
        rs = await update(form.value);
      } else {
        rs = await addNew(form.value);
      }
      if (rs.code == 200) {
        resetForm();
        getStaffPageList();
      }
    } else {
      console.log("报错啦！请重新试一下", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    id: "",
    insId: 0,
    realName: "",
    empNo: "",
    roleId: "",
    username: "",
    password: "",
    dataAuth: 0,
  };
  staffForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const updateStaffStatus = async (
  id: string | number,
  status: string | number
) => {
  ElMessageBox.confirm(status ? "确定启用吗" : "确定停用吗", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await upStatus({
        id: id,
        status: status,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: status ? "启用成功" : "停用成功",
        });
        getStaffPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getRoleList = async (): Promise<void> => {
  const rs = await allRole();
  if (rs.code == 200) {
    roleList.value = rs.payload;
  }
};
const getOrgList = async (): Promise<void> => {
  const rs = await allOrg();
  if (rs.code == 200) {
    orgList.value = rs.payload;
    if (route.params.id) {
      params.value.insId = parseInt(<string>route.params.id);
    } else {
      params.value.insId = rs.payload[0].id;
    }
  }
};

const { isShowBindWechat, currentUserInfo, showWechatBindDialog, unbindWechat } = useBindWechat()

const handleBindWechatFinished = () => {
  ElMessage.success('已成功绑定微信')
  isShowBindWechat.value = false
  getStaffPageList()
}

const _unbindWechat = async (row: any) => {
  const rs: any = await unbindWechat(row)

  if (rs.code === 200) {
    getStaffPageList();
  }
}
const handleCommand = (command: string, row: any) => {
  if (command === "updateStaffStatus") {
    updateStaffStatus(row.id, row.status == 1 ? 0 : 1)
  } else if (command === "delStaff") {
    delStaff(row.id)
  }
}
watch(params.value, (val) => {
  getStaffPageList();
});

// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getOrgList();
    getStaffPageList();
    getRoleList();
  },
  {
    deep: true
  }
)

onMounted(() => {
  getOrgList();
  getStaffPageList();
  getRoleList();
});
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  text-align: left;
  margin-top: 18px;
}

:deep(.el-table) {
  margin: 0 auto;
}

.page {
  margin: 10px auto;
}

.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}

:deep(.el-radio-group) {
  display: block;
}

:deep(.el-radio) {
  display: block;
}

.intro {
  margin-left: 20px;
  font-size: 12px;
}
</style>
